<template>
  <el-card shadow="always">
    <el-breadcrumb
      v-if="this.$route.query.name"
      separator-class="el-icon-arrow-right"
      style="padding: 20px"
    >
      <el-breadcrumb-item>学科管理</el-breadcrumb-item>
      <el-breadcrumb-item>{{ this.$route.query.name }}</el-breadcrumb-item>
      <el-breadcrumb-item>目录管理</el-breadcrumb-item>
    </el-breadcrumb>
    <div>
      <el-row>
        <el-col :span="16" style="height: 50px">
          <p>目录名称</p>
          <el-input v-model="directoryName" style="width: 240px" />
          <p>状态</p>
          <el-select v-model="value" placeholder="请选择" style="width: 215px">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-button style="margin-left: 10px" @click="delSearch">
            清除
          </el-button>
          <el-button type="primary" @click="startSearch">搜索</el-button>
        </el-col>
        <el-col :span="8" style="text-align: right; height: 50px">
          <el-button v-if="subjectID" type="text" @click="goback()">
            ←返回学科
          </el-button>
          <el-button type="success" icon="el-icon-edit" @click="addSubFn">
            新增目录
          </el-button>
        </el-col>
      </el-row>

      <alertVue :total="total" />

      <el-table v-loading="loading" :data="tableData">
        <el-table-column type="index" :index="indexMethod" label="序号" />
        <el-table-column prop="subjectName" label="所属学科" />
        <el-table-column prop="directoryName" label="目录名称" />
        <el-table-column
          prop="creatorID"
          label="创建者"
          :formatter="forMatterCreatorIDFn"
        />
        <el-table-column prop="addDate" label="创建日期">
          <template #default="{ row }">
            {{ row.addDate | formatTime('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>
        <el-table-column prop="totals" label="面试题数量" />
        <el-table-column
          prop="state"
          label="状态"
          :formatter="forMatterStateFn"
        />
        <el-table-column label="操作" width="220px">
          <template #default="{ row }">
            <el-button
              v-if="row.state"
              type="text"
              size="small"
              @click="
                row.state = !row.state
                stateDirectorys(row.id, row.state)
              "
            >
              禁用
            </el-button>
            <el-button
              v-else
              type="text"
              size="small"
              @click="
                row.state = !row.state
                stateDirectorys(row.id, row.state)
              "
            >
              启用
            </el-button>
            <el-button
              type="text"
              size="small"
              :disabled="Boolean(row.state)"
              @click="editDirectorys(row)"
            >
              修改
            </el-button>
            <el-button
              type="text"
              size="small"
              :disabled="Boolean(row.state)"
              @click="delDirectorys(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="block">
        <el-pagination
          :current-page="page"
          :page-sizes="[10, 15, 20, 25]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="currentChange"
        />
      </div>

      <addEditDirectorysVue
        :show-dialog.sync="showDialog"
        :row-directory-name="rowDirectoryName"
        :row-id="+rowId"
        :row-subject-id="+rowSubjectID"
        :flag="flag"
        @getDirectorysListFn="getDirectorysList()"
      />
    </div>
  </el-card>
</template>

<script>
import {
  getDirectorysListApi,
  delDirectorysApi,
  stateDirectorysApi
} from '@/api/subjects'
import addEditDirectorysVue from './components/add-edit-directorys.vue'
import obj from '@/const/subjects'
import alertVue from './components/alert.vue'

export default {
  components: {
    addEditDirectorysVue,
    alertVue
  },
  data() {
    return {
      flag: false,
      rowId: '', // 目录ID
      rowSubjectID: '', // 学科ID
      rowDirectoryName: '',
      directoryName: '', // 搜索目录
      tableData: [], // 目录列表
      total: 0, // 目录总数
      page: 1, // 当前页数
      pageSize: 10, // 每页显示的数据条数
      showDialog: false, // 添加目录弹层
      subjectID: undefined, // 学科ID
      loading: false,
      options: [
        {
          value: '1',
          label: '启用'
        },
        {
          value: '0',
          label: '禁用'
        }
      ],
      value: undefined
    }
  },
  watch: {
    // 监听路由是否变化
    $route() {
      this.getDirectorysList()
    }
  },
  created() {
    this.getDirectorysList()
  },
  methods: {
    goback() {
      this.$router.push({
        path: '/subjects/list'
      })
    },
    // 标签状态
    async stateDirectorys(id, state) {
      await stateDirectorysApi(id, state)
    },
    // 获取目录列表
    async getDirectorysList() {
      this.loading = true
      this.subjectID = this.$route.query.id
      const { data } = await getDirectorysListApi(
        this.page,
        this.pageSize,
        this.subjectID,
        this.directoryName,
        this.value
      )
      this.tableData = data.items
      this.total = data.counts
      this.rowId = ''
      this.rowSubjectID = ''
      this.rowDirectoryName = ''
      this.flag = Boolean(this.$route.query.id)
      this.loading = false
    },
    addSubFn() {
      this.directoryName = ''
      this.value = undefined
      this.showDialog = true
    },
    // 修改目录
    editDirectorys(row) {
      this.rowDirectoryName = row.directoryName
      this.rowId = row.id
      this.rowSubjectID = row.subjectID
      this.showDialog = true
    },
    // 删除目录
    async delDirectorys(id) {
      this.$confirm('此操作将永久删除该学科，是否继续？', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await delDirectorysApi(id)
          this.$message.success('删除成功')
          // bug1：删除了当前页数据，页码会跳到上一页，并且上一页数据丢失
          // bug2：所有数据只剩最后一条了，删除后，页码会变为0，所以要加判断
          // 如果仅剩最后一条数据了还删除成功了，这个时候应当页面减1
          if (this.tableData.length === 1 && this.page > 1) {
            this.page--
          }
          this.getDirectorysList()
        })
        .catch(() => {
          console.log('点击了取消')
        })
    },
    // 搜索目录
    async startSearch() {
      this.getDirectorysList()
    },
    // 清除搜索框
    delSearch() {
      this.directoryName = ''
      this.value = undefined
      this.getDirectorysList()
    },
    // currentPage 页码改变时会触发
    // 目标：页码切换渲染新一页的数据
    currentChange(val) {
      // 更新当前页
      this.page = val
      // 重新获取新的页码的数据
      this.getDirectorysList()
    },
    // pageSize 改变时会触发
    handleSizeChange(val) {
      // 更新每页条数
      this.pageSize = val
      // 更新每页条数时，页码重置为第一页
      // 原因：每页条数的变化后，当前页已经不是之前的当前页了，需要重置
      this.page = 1
      // 根据新的页码以及最新的数据条数，请求最新的的数据
      this.getDirectorysList()
    },
    indexMethod(index) {
      return index + 1 + (this.page - 1) * this.pageSize
    },
    forMatterStateFn(row, column, cellValue, index) {
      const { stateType } = obj
      // 根据 cellValue 去数组中，找相同的id项
      // 常量抽离，将用于判断的标识，抽离到常量模块
      // cellValue当前列的数据
      const result = stateType.find((item) => item.id === +cellValue)
      return result ? result.value : '未知'
    },
    forMatterCreatorIDFn(row, column, cellValue, index) {
      const { adminType } = obj
      // 根据 cellValue 去数组中，找相同的id项
      // 常量抽离，将用于判断的标识，抽离到常量模块
      // cellValue当前列的数据
      const result = adminType.find((item) => item.id === +cellValue)
      return result ? result.value : '未知'
    }
  }
}
</script>

<style scoped>
p {
  display: inline-block;
  width: 80px;
  padding-right: 10px;
  text-align: right;
}
</style>
